package com.sgb.member.weight;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.sgb.member.R;


public class MemberTypeLayoutManager extends LinearLayoutManager {
    Context context;
    private Rect displayRect;

    public MemberTypeLayoutManager(Context context) {
        super(context);
        this.context = context;
    }

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        if (getItemCount() <= 0 || state.isPreLayout()) {
            return;
        }
        TextView textView = null;
        Rect lastFrame = new Rect();
        if (displayRect == null) {
            displayRect = new Rect(0, 0, getHorizontallySpace(), getHeight());
        }
        detachAndScrapAttachedViews(recycler);
        for (int i = 0; i < getItemCount(); i++) {
            View scrap = recycler.getViewForPosition(i);
            addView(scrap);
            measureChildWithMargins(scrap, 0, 0);
            int width = getDecoratedMeasuredWidth(scrap);
            int height = getDecoratedMeasuredHeight(scrap);
            Rect frame = new Rect();
            frame.set(lastFrame.right, 0, lastFrame.right + width, height);
            if (displayRect.right >= frame.right + 20) {
                layoutDecorated(scrap, frame.left, frame.top, frame.right, frame.bottom);
                lastFrame = frame;
            } else {
                if (textView == null) {
                    textView = scrap.findViewById(R.id.tv_type);
                    textView.setText("...");
                    textView.setBackgroundColor(Color.WHITE);
                    textView.setTextColor(Color.parseColor("#ff5792fd"));
                    textView.setTextSize(10);
                    layoutDecorated(scrap, frame.left, frame.top, frame.right, frame.bottom);
                } else {
                    removeAndRecycleView(scrap, recycler);
                }
            }
        }
    }

    @Override
    public boolean canScrollHorizontally() {
        return false;
    }

    private int getHorizontallySpace() {
        return getWidth() - getPaddingEnd() - getPaddingStart();
    }
}
